<template>
    <el-form class="routerView" :model="ruleForm" ref="form" label-width="auto" size="medium" label-position="left" :rules="rules">  
        <h3>添加学生</h3>
        <div class="form">
            <el-form-item label="性别：" >
                <el-radio v-model="ruleForm.sex" label="男" @input="getDormitory" :disabled="isBuild">男</el-radio>
                <el-radio v-model="ruleForm.sex" label="女" @input="getDormitory" :disabled="isBuild">女</el-radio>
            </el-form-item>
            <el-form-item label="专业：" prop="dept">
                <el-select v-model="ruleForm.dept" filterable placeholder="请选择" :disabled="isBuild">
                    <el-option
                    v-for="item in Depts"
                    :key="item.deid"
                    :label="item.name"
                    :value="item.name">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="人数：" prop="peoplenum" class="inline-input">
                <el-input v-model="ruleForm.peoplenum" :disabled="isBuild"></el-input>
            </el-form-item><br>
        </div>
        <div class="button">
            <el-form-item size="large" label-width="0" style="margin-left:25px"> 
                <el-button type="success" @click="build">生成</el-button>
            </el-form-item>
            <el-form-item size="large" label-width="0" style="margin-left:25px"> 
                <el-button type="danger" @click="clear">重新输入</el-button>
            </el-form-item>
        </div>
        
        
        <hr>
        <table v-if="Students.length" class="table" border="1" cellspacing="0">
            <tr>
               <th>序号</th> 
               <th>姓名</th> 
               <th>电话</th> 
               <th>邮箱</th> 
            </tr>
            <tr v-for="i in currentPageSize" :key="page * pagesize + i">
                <td>
                    {{page * pagesize + i }}
                </td>
                <td>
                    <el-input v-model="Students[page * pagesize + i - 1].name"></el-input>
                </td>
                <td>
                    <el-input v-model="Students[page * pagesize + i - 1].phone" maxlength="11"></el-input>
                </td>
                <td>
                    <el-input v-model="Students[page * pagesize + i - 1].email"></el-input>
                </td>
            </tr>
        </table>
        <el-form-item v-if="Students.length" >
            <el-pagination
                background
                layout="prev, pager, next"
                :page-size="pagesize"
                :total="Students.length"
                style="text-align: center"
                :current-page="currentPage"
                @current-change="pageChange">
            </el-pagination>
        </el-form-item>
        <el-form-item size="large" label-width="0" style="text-align: center;display:block"> 
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
export default {
    name:'Addstudent',
    data() {
        return {
            ruleForm:{
                dept:'',
                sex:'男',
                peoplenum:'',
            },
            index:1,
            page:0,
            currentPage:1,
            pagesize:6,
            currentPageSize:0,
            Students:[],
            Dormitory:[],
            newDormitory:[],
            Depts:[],
            deid:'',
            all:0,  
            countStu:0,
            isBuild:false,
            rules:{
                dept:[{ required:true,message:'专业信息不能为空',trigger:'blur' }],
                peoplenum:[{ required:true,message:'人数不能为空',trigger:'blur' }],
                name:[{ required:true,message:'姓名不能为空',trigger:'blur' }],
                phone:[{ required:true,message:'电话不能为空',trigger:'blur' }],
                email:[{ required:true,message:'邮箱不能为空',trigger:'blur' }],
            }
        }
    },
    computed:{
        idprv:function () {
            this.Depts.forEach(dept=>{
                if(dept.name == this.ruleForm.dept){
                    this.deid=dept.deid
                    return
                }
            })
            if(parseInt(this.deid)<10)
                    this.deid = '0'+this.deid
            return new Date().getFullYear() + this.deid
        }
    },
    methods:{
        onSubmit(){
            let _this = this
            let arr = Array('qq.com','163.com','139.com','sina.com','yeah.com','126.com','21cn.com','gmail.com','yahoo.com','msn.com','hotmail.com','aol.com','ask.com','live.com','3721.net','googlemail.com','mail.com','0355.net')
            for(let i in _this.Students){
                if(_this.Students[i].name == '' || _this.Students[i].phone == '' || _this.Students[i].email == '' ){
                    alert(_this.Students[i].sid+'的信息未写全')
                    return
                }
                if(_this.Students[i].phone.length < 11 || isNaN(parseInt(_this.Students[i].phone)) || _this.Students[i].phone.slice(0,1) != '1'){
                    alert(_this.Students[i].sid+'电话输入有误')
                    return
                }
                if(_this.Students[i].email.split('@')[0] == '' || !arr.includes(_this.Students[i].email.split('@')[1])){
                        alert(_this.Students[i].sid+'邮箱地址有误')
                        return
                }
            }
            this.Students.sort((a,b)=>{
                if(a.name<b.name)
                    return -1
                else if(a.name>b.name)
                    return 1
                else return 0
            })
            let no = ''
            for(let i = 0;i < this.Students.length;i++){
                if(i+this.countStu<9)
                    no = '00'+(i+1+this.countStu)
                else if(i+this.countStu<99)
                    no = '0'+(i+1+this.countStu)
                this.Students[i].sid = this.idprv + no
            }
            axios.post('http://localhost:8081/student/addStudents',_this.Students).then(function(){
                for(let i=0;i<_this.newDormitory.length;i++){
                    if(_this.newDormitory[i].isChange){
                        console.log(_this.newDormitory[i].dorid+"变化了");
                        _this.editDorPo(_this.newDormitory[i].dorid,_this.newDormitory[i].population)
                    }
                }
                alert('添加成功')
                _this.clear()
                _this.all = 0
                _this.getDormitory()
            }).catch(function(){
                alert('添加失败')
            })
            console.log(this.Dormitory);
        },
        getDorNum(){
            const _this = this
            return new Promise((resolve,reject)=>{
                axios.get(`http://localhost:8081/dormitory/countAllSpace?sex=${_this.ruleForm.sex}`).then(res=>{
                    resolve(res.data)
                }).catch(err=>{
                    reject(err)
                })
            })
        },
        async getDormitory(){
            this.Dormitory = await this.getDorNum()
            let exitNum=0
            for(let i=0;i<this.Dormitory.length;i++){
                if(this.Dormitory[i].population!=0)
                    exitNum+=this.Dormitory[i].population
                    this.Dormitory[i] = {isChange:false,...this.Dormitory[i]}
            }
            this.all = this.Dormitory.length*6-exitNum;
            console.log(this.all);
        },
        getCountStu(){
            const _this = this
            axios.get(`http://localhost:8081/student/getNumOfSameStu?sid=${this.idprv}`).then(res=>{
                _this.countStu = res.data
            })
        },
        getDepts(){
            let _this = this
            axios.get("http://localhost:8081/dept/getAll").then(res=>{
                _this.Depts=res.data
            })
        },
        editDorPo(dorid,num){
            console.log(dorid);
            dorid = dorid.split("#")
            axios.get(`http://localhost:8081/dormitory/editPoAtDor/${dorid[0]}/${dorid[1]}?num=${parseInt(num)}`)
        },
        build(){
            let _this = this
            let num ;
            this.clear()
            if(this.ruleForm.dept == ''){
                alert('专业未选择，请重新选择')
                return
            }
            if(parseInt(this.ruleForm.peoplenum)<=0 || isNaN(parseInt(this.ruleForm.peoplenum))){
                alert('人数输入有问题，请重新输入')
                return
            }
            if(parseInt(this.ruleForm.peoplenum)>this.all){
                alert('抱歉剩余的宿舍不够了')
                return
            }
            this.isBuild = true
            this.getCountStu()
            num = parseInt(this.ruleForm.peoplenum)
            for(let i=0;i<_this.Dormitory.length;i++){
                if(_this.Dormitory[i].population < 6)
                    for(;_this.index <= num;_this.index++){
                        _this.Dormitory[i].isChange = true
                        _this.Students.push({
                            sid:'',
                            name:'',
                            sex:_this.ruleForm.sex,
                            dept:_this.ruleForm.dept,
                            dorid:_this.Dormitory[i].dorid,
                            phone:'',
                            email:''
                        })
                        if(++_this.Dormitory[i].population == 6){
                            _this.index++
                            break
                        }
                    }
            }
            if((this.Students.length - this.page * this.pagesize)/this.pagesize >= 1){
                this.currentPageSize = this.pagesize
            }else this.currentPageSize = this.Students.length
            this.newDormitory = this.Dormitory
        },
        pageChange(currentPage){
            this.page = currentPage - 1
            if((this.Students.length - this.page * this.pagesize)/this.pagesize >= 1){
                this.currentPageSize = this.pagesize
            }else this.currentPageSize = (this.Students.length - this.page * this.pagesize)%this.pagesize
        },
        clear(){
            this.Students = []
            this.index = 1
            this.page = 0
            this.currentPage = 1
            this.currentPageSize = 0
            this.getDormitory()
            this.isBuild = false
        }
    },
    mounted(){
        this.getDormitory()
        this.getDepts()
    }
}
</script>

<style scoped>
    .form{
        display: flex;
        justify-content: space-between;
    }
    .button{
        text-align: center;
    }
    .el-form{
        padding: 20px;
        width: 80%;
    }
    .el-form-item{
        display: inline-block;
        text-align: left;
    }
    .inline-input{
        display: inline-block;
        width: 180px;
    }
    .table{
        width: 100%;
        text-align: center;
    }
    .table .el-input{
        border: 0;
        outline: none;
    }
    .routerView{
        padding: 20px;
        border-radius: 5px;
        position: relative;
        background-color: #fff;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        box-shadow: 3px 3px 6px 2px rgba(0, 0, 0, 0.5);
    }
</style>